package com.example.basic.custom;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.basic.utils.AddressUtils;
import com.example.basic.utils.IpUtils;
import com.example.basic.utils.StringUtils;
import com.example.basic.web.model.log.OperLog;
import com.example.basic.web.service.common.CommonService;
import com.example.basic.web.service.log.OperLogService;
import io.swagger.models.HttpMethod;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;

/**
 * @Author：syp
 * @Package：com.example.basic.custom
 * @Project：bajiao-device
 * @name：MyLogAspect
 * @Date：2023/9/6 10:25
 * @Filename：MyLogAspect
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class MyLogAspect {

    private final OperLogService sysOperLogService;

    @Resource
    private CommonService commonService;

    /**
     * 处理完请求后执行
     *
     * @param joinPoint     切入点对象
     * @param controllerLog @Log注解对象
     * @param jsonResult    返回值对象
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, jsonResult, null);
    }

    /**
     * 处理请求异常后执行
     *
     * @param joinPoint
     * @param controllerLog
     * @param e
     */
    @AfterThrowing(pointcut = "@annotation(controllerLog)", throwing = "e")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Throwable e) {
        handleLog(joinPoint, controllerLog, null, e);
    }

    /**
     * 记录日志
     *
     * @param joinPoint
     * @param controllerLog
     * @param e
     * @param jsonResult
     */
    private void handleLog(JoinPoint joinPoint, Log controllerLog, Object jsonResult, Throwable e) {
        try {
            //获取HttpServletRequest对象
            HttpServletRequest request = getRequest();
            //获取ip地址
            String requestIp = IpUtils.getIpAddr(request);
            //获取请求地址
            String requestUrl = request.getRequestURI();
            //获取类全名
            String classFullName = joinPoint.getTarget().getClass().getName();
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            //方法名称
            String methodName = methodSignature.getMethod().getName();
            //POST、GET、PUT、DELETE
            String requestMethod = request.getMethod();
//            String operationLocation = AddressUtils.getRealAddressByIP(requestIp);

            String userName = Objects.isNull(request.getAttribute("userCode")) ? "" : request.getAttribute("userCode").toString();
            //保存日志
            OperLog sysOperLog = new OperLog();
            sysOperLog.setStatus("SUCCESS");
//            sysOperLog.setOperationLocation(operationLocation);
            sysOperLog.setRequestIp(requestIp);
            sysOperLog.setRequestUrl(requestUrl);
            sysOperLog.setMethod(classFullName + "." + methodName);
            sysOperLog.setRequestMethod(requestMethod);
            sysOperLog.setCreateBy(userName);
            sysOperLog.setCreateAt(commonService.getDataBaseTime());
            //获取注解中对方法的描述信息 用于Controller层注解 请求参数、响应参数设置
            getControllerMethodDescription(joinPoint, controllerLog, sysOperLog, jsonResult);
            if (e != null) {
                //操作状态（0正常 1异常）
                sysOperLog.setStatus("0");
                sysOperLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            sysOperLogService.add(sysOperLog);
        } catch (Exception err) {
            if (e != null) {
                log.error("方法执行后异常通知，执行错误：{}", err.getMessage());
            } else {
                log.error("方法执行成功返回通知，执行错误：{}", err.getMessage());
            }
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     * 请求参数、响应参数设置
     *
     * @param joinPoint
     * @param controllerLog
     * @param sysOperLog
     * @param jsonResult
     */
    private void getControllerMethodDescription(JoinPoint joinPoint, Log controllerLog, OperLog sysOperLog, Object jsonResult) {
        //接口所属模块
        String title = controllerLog.title();
        //接口功能描述
        String description = controllerLog.description();
        sysOperLog.setDescription(description);
        sysOperLog.setTitle(title);
        //判断是否需要保存请求参数
        if (controllerLog.isSaveRequestData()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, sysOperLog);
        }
        //判断是否需要保存响应数据
        if (controllerLog.isSaveResponseData() && !ObjectUtils.isEmpty(jsonResult)) {
            sysOperLog.setJsonResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000));
        }

    }

    /**
     * 保存请求参数
     *
     * @param joinPoint
     * @param sysOperLog
     */
    private void setRequestValue(JoinPoint joinPoint, OperLog sysOperLog) {
        //获取请求参数
        String requestMethod = sysOperLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            sysOperLog.setOperatorParam(StringUtils.substring(params, 0, 2000));
        } else if (HttpMethod.GET.name().equals(requestMethod)) {
            Map<?, ?> paramsMap = (Map<?, ?>) getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            log.info("paramsMap:{}", paramsMap);
            Map<String, String[]> parameterMap = getRequest().getParameterMap();
            sysOperLog.setOperatorParam(StringUtils.substring(JSON.toJSONString(parameterMap), 0, 2000));
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            log.info("paramsMap:{}", paramsMap);
            sysOperLog.setOperatorParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
        }

    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (!ObjectUtils.isEmpty(o) && !isFilterObject(o)) {
                    try {
                        Object jsonObj = JSON.toJSON(o);
                        params += jsonObj.toString() + " ";
                    } catch (Exception e) {
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }

    /**
     * 获取request对象
     *
     * @return
     */
    private HttpServletRequest getRequest() {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) attributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        return request;
    }
}
